package com.Example.cert;


import com.Example.Model.Transfer.Transfer;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;

/**
 * 生成transfer json 文件
 * jks从node6开始，transfer从node5开始
 *
 * @author zyf
 */
public class GenerateTransferJson {

    public static void main(String[] args) throws Exception {

        // 新建存放transfer_json文件的目录
        File folder = new File("newJson");
        if (!folder.isDirectory()) {
            folder.mkdir();
        }

        // 过滤掉非节点node的jks，如果是国密，则使用目录newPfx，后缀为pfx过滤
        File fileDir = new File("newJks");

        File[] files = fileDir.listFiles(file -> file.getName().endsWith("jks") && file.getName().contains("node"));

        HashMap<String, String> map = new HashMap<>();

        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getName();
            String[] fileNameSplit = fileName.split("\\.");
            map.put(fileNameSplit[1], fileNameSplit[0]);
        }

        String from = "921000006e0012v696";
        String to = "";
        Transfer transfer = new Transfer();
        for (int i = 1; i <= map.size(); i++) {
            to = map.get("node" + (i + 5));
            transfer.setFrom(from);
            transfer.setTo(to);
            transfer.setAmount(5);
            String transferPath = "newJson/" + "transfer_" + from + ".node" + (i + 4) + ".json";
            writeTxrJsonToFile(transfer, transferPath);
            from = to;
        }

        writeTxrJsonToFile(new Transfer(from, "121000005l35120456", 5),
                "newJson/" + "transfer_" + from + ".node" + (map.size() + 5) + ".json");
    }

    /**
     * @param transfer
     * @param transferPath
     * @throws Exception
     */
    private static void writeTxrJsonToFile(Transfer transfer, String transferPath) throws Exception {
        String transferJson = JSON.toJSONString(transfer);
        File tranJsonFile = new File(transferPath);
        if (!tranJsonFile.exists()) {
            tranJsonFile.createNewFile();
        }
        FileUtils.writeStringToFile(tranJsonFile, transferJson, Charset.defaultCharset());
    }

}
